$(function () {
    $.initPage(templateList.load.start);
});

var templateList = new BaseFrame();

templateList.addBlock('search', 'list', 'pagination', 'detail');

//load module
templateList.load.addStart(function () {
    var params = templateList.data.search.params;
    $.get(_apiPath + '/Admins/Templates', params)
        .then(function (data) {
            _data = $.extend({}, data);
            return $.pageStart(_adminSettings);
        })
        .then(function () {
            templateList.load.runTask();
            templateList.event.runTask();
            templateList.load.list.create(_data.templateList);
        });
});

templateList.load.addBind('createTitle', function () {
    var currentPage = $.getCurrentPage(_adminSettings.pageList);
    $('title').text(currentPage.title);
});

templateList.load.addBind('createNav', function () {
    $('#logout').on('click', $.logoff);
    var navList = $.getUserAuthorityList(_user.roleList, _adminSettings.authorityList, _adminSettings.pageList);
    $('#block-nav').createNavList(navList).removeClass('dn');
});

templateList.load.list.addBind('createListTitle', function () {
    var currentPage = $.getCurrentPage(_adminSettings.pageList);
    $('#block-list .panel-title').text($.toString(currentPage.title));
});

templateList.load.list.addEvent('create', function (dataList) {
    if (dataList.length == 0) {
        $('#block-alert').text(_enumMessage.noSearchResult);
        $('#list-list tbody').addClass('dn');
        $('#block-alert').removeClass('dn');
        $('#block-pagination').addClass('dn');
    } else {
        var template = $('#template-list-detail').html();
        $('#list-list tbody').empty().createListTemplate(template, dataList);
        // templateList.load.pagination.create(_data.pageTotal);
        $('#list-list tbody').removeClass('dn');
        $('#block-alert').addClass('dn');
    }
    $('#block-list').removeClass('dn');
});

templateList.load.list.addEvent('update', function (pageNumber) {
    var params = templateList.save.search.params();
    console.log(params)
    $.get(_apiPath + '/Admins/Templates', params)
        .then(function (data) {
            _data = $.extend({}, data);
            templateList.load.list.create(_data.templateList);
            return $.pageStart(_adminSettings);
        })
    // .then(function () {
    //     templateList.load.runTask();
    //     templateList.event.runTask();
    //     templateList.load.list.create(_data.templateList);
    // });
});

templateList.load.pagination.addEvent('create', function (pageTotal, pageNumber, pageSize) {
    if ($.isEmpty(pageTotal) || pageTotal < 1) return;
    pageNumber = pageNumber || templateList.data.search.params.pageNumber;
    pageSize = pageSize || templateList.data.search.params.pageSize;
    $('#block-pagination').empty().createPagination({
        pageNumber: pageNumber,
        pageTotal: pageTotal,
    }).removeClass('dn');
});

templateList.load.addEvent('status', function (status) {
    if ($.isZero(status)) return '激活';
    return '未激活';
});

//event module
templateList.event.list.addBind('operation', function () {
    $('#list-list').on('click', '.btn[create]', function () {
        var detailData = $.extend({}, templateList.data.detail.params);
        templateList.load.detail.create(detailData);
        $('#modal-detail').modal('show');
    });

    $('#list-list').on('click', '.btn[update]', function () {
        var detailData = $.extend({}, templateList.data.detail.params, $(this).parents('tr[data]').data('data'));
        templateList.load.detail.create(detailData);
        $('#modal-detail').modal('show');
    });

    $('#list-list').on('click', '.btn[delete]', function () {
        var detailData = $.extend({}, $(this).parents('tr[data]').data('data'));
        $.confirm(templateList.message.list.deleteDetail, function () {
            templateList.form.deleteDetail(detailData);
        });
    });

    $('#list-list').on('click', '.btn[showTemplate]', function (e) {
        _data.templateList[e.target.name].emailBody = _data.templateList[e.target.name].emailBody.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
        $('#modal-template-detail-content').empty().html(_data.templateList[e.target.name].emailBody);
        $('#modal-template-detail').modal('show');
    })
});

templateList.load.detail.addEvent('create', function (detailData) {
    var domStorage = $('#form-detail');
    detailData.emailBody = !detailData.emailBody ? '' : detailData.emailBody.replace(/&lt;/g, '<').replace(/&gt;/g, '>')
    domStorage.data('detail', $.extend({}, detailData));
    // 给formList添加name节点
    _data.formList.map(function (item) {
        item.name = item.formChineseName;
    })
    $('#template-form-id').empty().createSelect(domStorage, 'detail.formId', $.getKeyValueListByIdName(_data.formList), {
        required: true,
    });
    $('#template-name').empty().createString(domStorage, 'detail.name', {
        required: true,
    });
    $('#template-subject').empty().createString(domStorage, 'detail.subject', {
        required: true,
        attributes: { maxlength: 1000 }
    });
    $('#template-priority').empty().createString(domStorage, 'detail.priority', {
        required: true,
        attributes: { maxlength: 1000 }
    });
    $('#template-email-body').empty().createTextarea(domStorage, 'detail.emailBody', {
        required: true,
        attributes: { maxlength: 10000 }
    });
    $('#temolate-status').empty().createSingleCheckbox(domStorage, 'detail.status', {
        reverse: true,
        isNumber: true,
    });

    // domStorage.data('detail').roleList = [];
    // for (var i = 0; i < detailData.roleList.length; i++)
    //     domStorage.data('detail').roleList.push(detailData.roleList[i].id);
    // var disabled = [];
    // for (var i = 0; i < _data.roleList.length; i++) {
    //     if (_data.roleList[i].isDefault) disabled.push(_data.roleList[i].id);
    //     if ($.isEmpty(domStorage.data('detail').roleList)) domStorage.data('detail').roleList.push(_data.roleList[i].id);
    // }
    // $('#field-detail-role').empty().createCheckbox(domStorage, 'detail.roleList', $.getKeyValueListByIdName(_data.roleList), {
    //     required: true,
    //     disabled: [1, 2],
    // });
    // domStorage.data('detail').formIdList = [];
    // var formList = [];
    // _data.formList.forEach(function (item) {
    //     formList.push({
    //         id: item.id,
    //         name: item.formChineseName
    //     });
    // });
    // if (!$.isEmpty(detailData.others)) {
    //     if (detailData.others.formIds === 0 || $.isEmpty(detailData.others.formIds)) { // all selected
    //         _data.formList.forEach(function (item) {
    //             domStorage.data('detail').formIdList.push(item.id);
    //         });
    //     } else {
    //         detailData.others.formIds.forEach(function (item) {
    //             domStorage.data('detail').formIdList.push(item);
    //         });
    //     }
    // } else { // all selected
    //     _data.formList.forEach(function (item) {
    //         domStorage.data('detail').formIdList.push(item.id);
    //     });
    // }
    // $('#field-detail-form').empty().createCheckbox(domStorage, 'detail.formIdList', $.getKeyValueListByIdName(formList), {
    //     required: true,
    //     allSelected: true
    // });
    // $('#field-detail-status').empty().createSingleCheckbox(domStorage, 'detail.status', {
    //     reverse: true,
    //     isNumber: true,
    // });
});

templateList.event.detail.addBind('operation', function () {
    $('#modal-detail').on('submit', '#form-detail', function (event) {
        var thisDom = $(this);
        var params = thisDom.data('detail');
        thisDom.find('[form]').findFormUnit().verifyClean();
        if (!templateList.verify.detail.params(params)) return false;
        !params.id ? params.id = 0 : 0;
        templateList.form.saveDetail(params);
        return false;
    });
});

templateList.load.search.addBind('create', function() {
    // if (eLancoApprovalList.verify.isSubmitModel()) return;
    var domStorage = $('#form-search');
    $('#field-search-type').createSelect(domStorage, 'search.formId', $.getKeyValueList('id', 'formChineseName', _data.formList), {
        verify: false,
        firstOption: _allSelect,
    });
    $('#field-search-Keywords').createString(domStorage, 'search.Keywords', $.getKeyValueList('id', 'formChineseName', _data.formList), {
        verify: false,
    });

    $('#block-search .search-item[formId]').hide();
    $('#block-search').removeClass('dn');
});

templateList.save.search.addEvent('params', function(pageNumber) {
    var data = $('#form-search').data();
    return data.search;
});

templateList.event.search.addBind('operation', function() {
    $('#block-search').on('click', '#search-btn', function() {
        templateList.load.list.update(1);
        return false;
    });
});

templateList.form.addEvent('saveDetail', function (params) {
    params.emailBody = params.emailBody.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
    $.post(_apiPath + '/Admins/Template/' + params.id + '/Save', params)
        .then(function (result) {
            console.log(window.sessionStorage.getItem('user'));
            if (_user.id === params.id) { _user.others = { formIds: params.formIdList }; window.sessionStorage.setItem('user', JSON.stringify(_user)); }
            console.log(window.sessionStorage.getItem('user'));
            $('#modal-detail').modal('hide');
            $.alert(_enumMessage.saveSuccess, templateList.load.list.update);
        });
});

templateList.form.addEvent('deleteDetail', function (params) {
    $.delete(_apiPath + '/Admins/Template/' + params.id, params)
        .done(function (result) {
            $.alert(_enumMessage.deleteSuccess, templateList.load.list.update);
        });
});

//verify module
templateList.verify.detail.addEvent('params', function (params) {
    var judge = true;
    if ($.isEmpty(params.formId)) {
        judge = false;
        $('#template-form-id').verifyErrorAndHelp(templateList.message.detail.formIdRequired);
    }
    if ($.isEmpty(params.name)) {
        judge = false;
        $('#template-name').verifyErrorAndHelp(templateList.message.detail.nameRequired);
    }
    if ($.isEmpty(params.subject)) {
        judge = false;
        $('#template-subject').verifyErrorAndHelp(templateList.message.detail.subjectRequired);
    }
    if ($.isEmpty(params.emailBody)) {
        judge = false;
        $('#template-email-body').verifyErrorAndHelp(templateList.message.detail.emailBodyRequired);
    }

    return judge;
});


templateList.message.list.addConfig('deleteDetail', '是否删除detail');
templateList.message.detail.addConfig('formIdRequired', '所属表单必填');
templateList.message.detail.addConfig('nameRequired', '名称必填');
templateList.message.detail.addConfig('subjectRequired', '标题必填');
templateList.message.detail.addConfig('emailBodyRequired', '内容必填');